<template>
  <div style="border: 1px solid #ccc; padding: 10px; border-radius: 10px; margin: 10px 0; width: 222px">
    <!--Video display-->
    <video
        ref="video"
        width="200"
        height="150.4"
        autoplay
        class="mt20"
        style="background: #d9d9d9"
    ></video>

    <div style="color: #000000; margin: 10px 0;">
      <span>Examinee name: {{ user.nickname }}</span><br>
    </div>
    <div style="color: #000000; margin: 10px 0;">
      <span>Violation count: {{violateCount}} / 3</span><br>
    </div>
    <div style="color: #ff0000; margin: 10px 0;" v-show="isPhoto">
      <span>Warning image:</span><br>
      <!--Capture stream with canvas-->
      <canvas ref="canvas" width="200" height="150.4" style="background-color: #eaeaea"></canvas>
    </div>
  </div>

</template>

<script>
export default {
  name: "FaceDetect",
  data() {
    return {
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      violateCount: 0,
      remindCount: 0,
      isCamera: false,
      isPhoto: false,
    };
  },
  // Loop controller
  mounted() {
    this.timer = setInterval(() => {
      if (this.isCamera) {
        this.photograph();
        this.commit()
      }
    }, 5000);
  },

  created() {
    this.callCamera()
  },
  methods: {
    // Call the camera
    callCamera() {
      console.log(this.isCamera);
      // Use H5 API to call the computer camera
      navigator.mediaDevices
        .getUserMedia({
          audio: true, // enable audio
          video: true, // enable video
        })
        .then((success) => {
          var videoTracks = success.getVideoTracks();
          this.$refs["video"].srcObject = success;
          this.isCamera = true;
          // Real-time photo effect
          this.$refs["video"].play();
        })
        .catch((error) => {
          console.error("Failed to turn on the camera, please check if it is available!");
        });
    },
    // Take a photo
    photograph() {
      let ctx = this.$refs["canvas"].getContext("2d");
      ctx.drawImage(this.$refs["video"], 0, 0, 200, 150.4);
      let imgBase64 = this.$refs["canvas"].toDataURL("image/jpeg", 0.7);
      let str = imgBase64.replace("data:image/jpeg;base64,", "");
      this.base64 = str;
    },
    // Close camera
    closeCamera() {
      this.isCamera = false
      if (!this.$refs["video"].srcObject) return;
      let stream = this.$refs["video"].srcObject;
      let tracks = stream.getTracks();
      tracks.forEach((track) => {
        track.stop();
      });
      this.$refs["video"].srcObject = null;
    },
    // Submit for face verification
    commit() {
      // Get the Canvas object
      let canvas = this.$refs["canvas"]
      var formData = new FormData();
      var base64File = canvas.toDataURL("image/jpeg", 0.7);
      //var userName = $("#userName").val();
      formData.append("file", base64File);
      formData.append("name", this.user.username);
      formData.append("groupId", "101");
      $.ajax({
        type: "post",
        url: "http://localhost:8089/faceSearch",
        data: formData,
        contentType: false,
        processData: false,
        async: false,
        success: (text) => {
          var res = JSON.stringify(text)
          if (text.code == 0 && this.user.username == text.data.name) {
            this.remindCount = 0
            this.isPhoto = false
            // this.$message({
            //   message: 'Face verification succeeded',
            //   type: 'success'
            // });
          } else {
            this.remind()
          }
        },
        error: function (error) {
          alert(JSON.stringify(error))
        }
      });
    },

    remind() {
      this.isPhoto = true
      this.remindCount++
      if (this.remindCount === 3) {
        this.violate()
        this.remindCount = 0
      } else {
        this.$message({
          message: 'No face detected or face does not match, please adjust in time',
          type: 'warning'
        });
      }
    },
    violate() {
      this.violateCount++
      if (this.violateCount === 3) {
        //this.$message.error('The number of violations has reached the upper limit and the exam is over');
        this.closeCamera()
        this.$emit('submit');
        alert('The number of violations has reached the upper limit and the exam is over')
      } else {
        this.$message.error('Multiple instances of no face detection or face mismatch, record one violation');
      }
    },

  }
}
</script>
